package com.wanbo.springbootwx.service;


import com.wanbo.springbootwx.entity.BaseMessage;
import com.wanbo.springbootwx.entity.ImageMessage;
import com.wanbo.springbootwx.entity.TextMessage;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WxutilService {

    private static final String TOKEN = "wanbo";

    public static boolean check(String timestamp, String nonce, String signature)  {
        // 1）将token、timestamp、nonce三个参数进行字典序排序
        String [] strs = new String[]{TOKEN,timestamp,nonce};
        Arrays.sort(strs);
        // 2）将三个参数字符串拼接成一个字符串进行sha1加密
        String str = strs[0]+strs[1]+strs[2];

        String mysig = sha1(str);
        System.out.println(mysig);
        System.out.println(signature);

        // 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        return mysig.equalsIgnoreCase(signature);
    }

    // 进行sha1加密
    private static String sha1(String str)  {
        try {
            //获取加密对象
            MessageDigest md = MessageDigest.getInstance("sha1");
            //进行加密操作
            byte[] digest =md.digest(str.getBytes());
            char[] chars = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            StringBuilder sb = new StringBuilder();
            // 处理加密结果
            // 处理详解 获取的byte是8位， 8位带代表两个字节所以有高4位和低四位分开处理
            // 四位二进制代表 0-15
            for (byte b : digest){
                // 首先进行第四位的处理
                sb.append(chars[(b>>4)&15]);
                // 然后进行高四位的处理
                sb.append(chars[(b)&15]);
            }
            return sb.toString();
        }catch (Exception e){
//            System.out.println(e.printStackTrace());
        }
        return "0";
    }

    /**
     * 解析xml数据包
     * @param is
     * @return
     */
    public static Map<String, String> parseRequest(ServletInputStream is) {
        Map<String,String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        try {
            // 读取输入流，获取document对象
            Document document = reader.read(is);
            // 根据document获取根节点信息
            Element root = document.getRootElement();
            // 获取根节点获取所有的子节点
            List<Element> elements = root.elements();
            for (Element e:elements) {
                map.put(e.getName(),e.getStringValue());
            }
        }catch (DocumentException e){
            e.printStackTrace();
        }
        return  map;
    }

    /**
     * 用于处理所有的事件和消息回复
     * @param reqMap
     * @return
     */
    public static String getRespose(Map<String, String> reqMap) {
        BaseMessage msg;
        String msgType = reqMap.get("MsgType");
        switch (msgType){
            // 处理文本消息
            case "text":
                msg = dealTextMessage(reqMap);
                break;
            case "image":
                msg = dealImageMessage(reqMap);
                break;
//            case "voice":
//
//                break;
//            case "music":
//
//                break;
//            case "news":
//
//                break;
//            default:
//                break;
        }
        return  null;
    }

    private static BaseMessage dealImageMessage(Map<String, String> reqMap) {
        ImageMessage img = new ImageMessage(reqMap,"");
        return img;
    }

    /**
     * 处理文本消息
     * @param reqMap
     * @return
     */
    private static BaseMessage dealTextMessage(Map<String, String> reqMap) {
        TextMessage tm = new TextMessage(reqMap,"你爱我吗？");
        return tm;
    }
}
